#!/usr/bin/env node

const http = require('http');
const fs = require('fs');
const path = require('path');

http.createServer((req, res) => {
  if (req.url !== '/' || req.method !== 'POST') {
    res.writeHead(404);
    res.end('404 Not Found');
    return;
  }

  let boundary = req.headers['content-type'].split('boundary=')[1];
  let chunks = [];
  req.on('data', chunk => {
    chunks.push(chunk);
  });
  req.on('end', () => {
    let body = Buffer.concat(chunks).toString();
    let parts = body.split(`--${boundary}`);
    parts.forEach(part => {
      let partHeaders = {};
      let headers = part.split('\r\n');
      for (let i = 0; i < headers.length - 1; i++) {
        if (headers[i] !== '') {
          let header = headers[i].split(': ');
          partHeaders[header[0]] = header[1];
        }
      }
      let data = headers[headers.length - 1];

      if (partHeaders['content-disposition'] && partHeaders['content-disposition'].includes('form-data')) {
        let fieldName = partHeaders['content-disposition'].split('name="')[1].split('"')[0];
        if (partHeaders['content-disposition'].includes('filename="')) {
          let fileName = partHeaders['content-disposition'].split('filename="')[1].split('"')[0];
          let filePath = path.join(__dirname, 'uploads', fileName);
          fs.writeFileSync(filePath, data, { encoding: 'base64' });
          console.log(`Uploaded file: ${fileName}`);
        } else {
          console.log(`Received field: ${fieldName}`);
          console.log(`Received value: ${data}`);
        }
      }
    });

    res.writeHead(200);
    res.end('Data received!');
  });
}).listen(8080, () => {
  console.log('Server running at http://localhost:8080/');
});
